import time

from selenium.webdriver import Keys, ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webdriver import WebDriver


class KeyCode:
    RIGHT = '68'
    LEFT = '65'
    UP = '87'
    DOWN = '83'


class Movement:
    def __init__(self, driver: WebDriver):
        self.driver = driver

    def send_key_down(self, keyCode):
        down_script = "var event = new KeyboardEvent('keydown', {keyCode:" + keyCode + "});window.dispatchEvent(event)"
        self.driver.execute_script(down_script)

    def send_key_up(self, keyCode):
        up_script = "var event = new KeyboardEvent('keyup', {keyCode:" + keyCode + "});window.dispatchEvent(event)"
        self.driver.execute_script(up_script)

    def keep_key_press(self, keyCode, seconds):
        self.send_key_down(keyCode)
        time.sleep(seconds)
        self.send_key_up(keyCode)
        time.sleep(0.1)

    def esc(self):
        self.driver.find_element(By.TAG_NAME, 'html').send_keys(Keys.ESCAPE)

    def key_press(self, keyCode, duration=0.2):
        down_script = "var event = new KeyboardEvent('keydown', {keyCode:" + str(
            keyCode) + "});window.dispatchEvent(event)"
        self.driver.execute_script(down_script)
        time.sleep(duration)
        up_script = "var event = new KeyboardEvent('keyup', {keyCode:" + str(keyCode) + "});window.dispatchEvent(event)"
        self.driver.execute_script(up_script)
        time.sleep(0.1)

    def keep_move_right(self, seconds):
        self.keep_key_press('68', seconds)

    def keep_move_left(self, seconds):
        self.keep_key_press('65', seconds)

    def keep_move_up(self, seconds):
        self.keep_key_press('87', seconds)

    def keep_move_down(self, seconds):
        self.keep_key_press('83', seconds)

    def move_right(self, steps, duration=0.2):
        for _ in range(steps):
            self.key_press('68', duration)

    def move_up(self, steps, duration=0.2):
        for _ in range(steps):
            self.key_press('87', duration)

    def move_down(self, steps, duration=0.2):
        for _ in range(steps):
            self.key_press('83', duration)

    def move_left(self, steps, duration=0.2):
        for _ in range(steps):
            self.key_press('65', duration)
